package org.wsiz.vro.web.domain;

import java.io.Serializable;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;
import org.wsiz.vro.domain.Address;
import org.wsiz.vro.repository.AddressRepository;
import org.wsiz.vro.web.domain.support.GenericSearchForm;

/**
 * SearchForm for {@link Address}
 */
@Component
@Scope("session")
public class AddressSearchForm extends GenericSearchForm<Address> implements Serializable {
    private static final long serialVersionUID = 1L;
    // make it static to avoid http://jira.springframework.org/browse/SWF-1224
    private static AddressRepository addressRepository;

    private Address address = new Address();

    @Autowired
    public AddressSearchForm(AddressRepository instance) {
        if (addressRepository == null) {
            addressRepository = instance;
        }
    }

    /**
     * Server side pagination with lazy model.
     * Automatically called by PrimeFaces component (via the GenericSearchForm).
     */
    @Override
    protected List<Address> load(PageRequest pageRequest) {
        Page<Address> page = addressRepository.findWithExample(address, pageRequest);
        setRowCount((int) page.getTotalElements());
        return page.getContent();
    }

    /**
     * The root address for search by example.
     * Used from the view.
     */
    public Address getAddress() {
        return address;
    }
}